//
//  LYVedioLiveController.m
//  LYLiveApp
//
//  Created by QD on 16/8/23.
//  Copyright © 2016年 览益信息科技. All rights reserved.
//

#import "LYVedioLiveController.h"
#import "OpenCONSTS.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "UIView+Frame.h"
#import "Masonry.h"
#import "LYUtil.h"
#import "LYCommentModel.h"
#import "UIImageView+WebCache.h"
#import "LYFuDaiView.h"
#import "LYLoginNewController.h"
#import "LYVideoInstance.h"
#import "LYSmallVideoView.h"
#import "LYSmallScreenSetView.h"
#import "WatchPlayBackViewController.h"
#import "LYAppDelegate.h"
#import "LYVideoPlayBackView.h"
#import "LYNTESController.h"
#import "LYShareSetView.h"


extern NSString *const LYCommentControllerInputBgHidden;
static const NSTimeInterval         kAnimationTime                = 0.2 ;
static const NSTimeInterval         kNavViewAnimationTime         = 3.0f;
static const NSTimeInterval         kStatementTotalTime           = 5;
static const NSTimeInterval         kStatementIntervalTime        = 1.0f;
static const CGFloat                kButtonViewHeight             = 35  ;
static const CGFloat                kIphone5ScreenWidth           = 320 ;
static const CGFloat                kMoviePlayerViewHeight        = 180 ;
static const CGFloat                kNotifyLabelFontSize          = 13.0f;
static const CGFloat                kNotifyViewHeight             = 30  ;
static const CGFloat                kReConnectTimes               = 3   ;
static const CGFloat                kTabbarHeight                 = 0  ;

UIKIT_STATIC_INLINE CGFloat MoviePlayerViewHeightWithScreenRate() {
    return kMoviePlayerViewHeight * SCREEN_WIDTH/kIphone5ScreenWidth;
}

UIKIT_STATIC_INLINE void ScreenRotateToPortrait(UIInterfaceOrientation orientation) {
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = orientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

@interface LYVedioLiveController () <VHallMoviePlayerDelegate,UIScrollViewDelegate,LYArticleInputViewDelegate,RequestDelegate>
@property (nonatomic,strong) UIWindow *window;
@property(nonatomic,strong) LYSmallVideoView *smallVideoView;
@property(nonatomic,strong) LYVideoPlayBackView *videoPlayBackView;
@property(nonatomic,strong) WatchPlayBackViewController *watchPlayBackVC;
@property(nonatomic,assign) BOOL isWatchPlayBack;   //观看视频回顾
@property(nonatomic,strong) UIImageView *bottomImageview;
@property(nonatomic,strong) LYShareSetView *shareSetView;

@end

@implementation LYVedioLiveController
#pragma mark ----- lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    LYIntroduceModel *roomModel = [LYIntroduceModel new];
    [LYLocalData sharedInstance].roomInfo = roomModel;
    
    _window = [[[UIApplication sharedApplication] delegate] window];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    if (isIPhoneX) {
        self.navViewTop.constant = 24;
        UIView *topBlackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        topBlackView.backgroundColor = [UIColor blackColor];
        [self.view addSubview:topBlackView];
    }
    [self _initData];
    
    [self.view addSubview:self.buttonView];
    [self.view addSubview:self.notifyView];
    [self.view addSubview:self.scrollView];
    [self.view insertSubview:self.scrollView belowSubview:self.notifyView];
    [self _addChildViewController];
    [self.view addSubview:self.commentInputView];
    self.commentInputView.hidden = YES;
    [self.view addSubview:self.inputBg];
    [self.view addSubview:self.rotateButton];
    [self.view addSubview:self.audioButton];
    [self.view addSubview:self.definitionView];
    [self.view addSubview:self.videoBottomView];
    [self _setupInputView];
    [self _resetTimer];
    [self.view addSubview:self.bottomImageview];
    self.navigationItem.title = @"视频解盘";
}

#pragma mark ------ Notification Action
- (void)videoBeginLoading {
    
    if (!self.inThisPage) {
        return;
    }
    [self _moviePlayerViewTap];
    [self.moviePlayer.moviePlayerView addSubview:self.indicator];
    self.indicator.center = self.moviePlayer.moviePlayerView.center;
    [self.indicator startAnimating];
}

- (void)videoFinishLoading {

    if (!self.inThisPage) {
        return;
    }
    [LYUtil hideHUDTo:self.moviePlayer.moviePlayerView];
    [self.indicator stopAnimating];
    [self.indicator removeFromSuperview];    
}

- (void)videoPlaySuccess {
        
    LYLog(@"videoPlaySuccessvideoPlaySuccess");
    
    if (!self.inThisPage) {
        return;
    }
    self.isNoVideoData = NO;
    [self.unWifiView removeFromSuperview];
    [self videoLiveBegin];
    [LYUtil hideHUDTo:self.view];
    [LYUtil hideHUDTo:self.window];

    [LYUtil hideHUDTo:self.moviePlayer.moviePlayerView];
    [self.indicator stopAnimating];
    [self.indicator removeFromSuperview];
}

- (void)videoPlayErrorHandel {
    
    if (!self.inThisPage) {
        return;
    }
    
    WS(weakSelf)
    [[SensorsAnalyticsSDK sharedInstance] track:@"LivingWatch"
                                 withProperties:@{
                                                  @"ly_living_type" :[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_type],
                                                  @"ly_living_definition":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_definition],
                                                  @"ly_living_succeed":@"成功",
                                                  @"ly_living_change_time":[LYUtil lySensorsString:[self _returnCurrentTime]],
                                                  @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                  }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.moviePlayer stopPlay];
        [LYUtil hideHUDTo:weakSelf.moviePlayer.moviePlayerView];
        [weakSelf.indicator stopAnimating];
        [weakSelf.indicator removeFromSuperview];
        [_noVideoView removeFromSuperview];
        _noVideoView = nil;
        _noVideoView.frame = weakSelf.moviePlayer.moviePlayerView.bounds;
        [weakSelf.moviePlayer.moviePlayerView addSubview:weakSelf.noVideoView];
        if (weakSelf.isFullScreen) {
            weakSelf.noVideoView.nvRotateBtn.hidden = NO;
        } else {
            weakSelf.noVideoView.nvRotateBtn.hidden = YES;
        }
//        weakSelf.moviePlayer.moviePlayerView.backgroundColor = RGB(155, 155, 155);
        weakSelf.isNoVideoData = YES;
        weakSelf.fullOverView.screenType = FullScreenTypeFail;
    });
}

- (void)videoFinishPlaying {
    
    if (!self.inThisPage) {
        return;
    }
    ScreenRotateToPortrait(UIInterfaceOrientationPortrait);
    [self.moviePlayer stopPlay];
    [self videoLiveFinished];
}

- (void)joinTeam:(NSNotification *)notify
{
    
    LYNTESController *ntesVC = [[LYNTESController alloc] initWithNibName:@"LYNTESController" bundle:nil];
    ntesVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:ntesVC animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    [[LYVideoInstance sharedInstance].moviePlayer stopPlay];
//    [[LYVideoInstance sharedInstance].moviePlayer destroyMoivePlayer];
//    [LYVideoInstance sharedInstance].moviePlayer = nil;

    
    
    [self.view addSubview:self.moviePlayer.moviePlayerView];
    [self.view bringSubviewToFront:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.navView aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.rotateButton aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.audioButton aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.definitionView aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.bottomImageview aboveSubview:self.moviePlayer.moviePlayerView];

    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO; // 控制整个功能是否启用。

    self.navBar.hidden = YES;
    self.inThisPage = YES;
    [self.tabBarController.view sendSubviewToBack:self.tabBarController.tabBar];
    [self _addNotification];
    [self _getLivingStatus];
    [self begainFullScreen];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    [[SensorsAnalyticsSDK sharedInstance] trackTimerBegin:@"LivingQuit"];
}

- (void)viewWillDisappear:(BOOL)animated {     
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.inThisPage = NO;
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    self.audioView.hidden = YES;
    [self _stopClickTimer];
    [self _stopStatementTimer];
    [self.fullOverView stopStatementTimer];
    if (self.isNotifyExpand) {
        [self expandNotifyView:nil];
    }
    
    if (self.isWatchPlayBack) {
        self.moviePlayer.moviePlayerView.hidden = NO;
    }
    [self endFullScreen];
    
}

- (void)_toSmallVideoView {
    
    if (self.isWatchPlayBack) {
        return;
    }
    
    //放widow上
    WS(weakSelf);
    weakSelf.smallVideoView = [LYSmallVideoView viewWithXib];
    
    if ([LYVideoInstance sharedInstance].smallVideoFrame.size.width == 0 && [LYVideoInstance sharedInstance].smallVideoFrame.size.height == 0) {
        if (isIPhoneX) {
            weakSelf.smallVideoView.frame = CGRectMake(SCREEN_WIDTH - 233 - 7, SCREEN_HEIGHT - 49 - 140 - 5 - 34, 233, 140);
        } else {
            weakSelf.smallVideoView.frame = CGRectMake(SCREEN_WIDTH - 233 - 7, SCREEN_HEIGHT - 49 - 140 - 5, 233, 140);
        }
    } else {
        weakSelf.smallVideoView.frame = [LYVideoInstance sharedInstance].smallVideoFrame;
    }
    weakSelf.smallVideoView.idString = [NSString stringWithFormat:@"%ld",(long)[LYLocalData sharedInstance].roomInfo.vhall.integerValue];
    weakSelf.smallVideoView.transform = CGAffineTransformIdentity;
    [weakSelf.indicator stopAnimating];
    [weakSelf.indicator removeFromSuperview];
    [_window addSubview:weakSelf.smallVideoView];
}


- (void)viewDidDisappear:(BOOL)animated {

    [super viewDidDisappear:animated];
    WS(weakSelf)
    [self.noVideoView removeFromSuperview];
    [self.finishedView removeFromSuperview];
    [self.unWifiView removeFromSuperview];
    
    self.navBar.hidden = NO;

//    [self.moviePlayer stopPlay];
    
    [[SensorsAnalyticsSDK sharedInstance] track:@"LivingQuit"
                                 withProperties:@{
                                                  @"ly_entry" :[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_entry],
                                                  @"ly_living_access_state":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_access_state],
                                                  @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                  }];
    
    [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:@"LivingQuit"
                                         withProperties:nil];
    
    if ([LYVideoInstance sharedInstance].isSmallScreen && [LYLocalData sharedInstance].roomInfo.living.integerValue == 1 && [LYVideoInstance sharedInstance].isPlaySuccess) {
        
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"LYSmallScreenSetView"]) {
            [self _toSmallVideoView];
            [self.moviePlayer pausePlay];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"LYSmallScreenSetView"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            LYSmallScreenSetView *setView = [LYSmallScreenSetView viewWithXib];
            setView.tag = 100102;
            [setView showInWindow];
            setView.useSmallScreenBlock = ^{
                NSString *idString;
                idString = [NSString stringWithFormat:@"%ld",(long)[LYLocalData sharedInstance].roomInfo.vhall.integerValue];
                if ([[LYLocalData sharedInstance] BoolValueForKey:kLYAppInAssess]) {
                    idString = [NSString stringWithFormat:@"507339787"];
                }
                NSDictionary *param = @{ @"id"               :idString,
                                         @"name"             :@"User000001",
                                         @"email"            :[LYLocalData sharedInstance].uuId
                                         };
                [[LYVideoInstance sharedInstance].moviePlayer reconnectPlay:param];
            };
        } else {
            [self _toSmallVideoView];
        }
        
    } else {
        [self.moviePlayer stopPlay];
    }
}

- (void)dealloc {
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
//    [self _destoryMoivePlayer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - notification events
- (void)keyboardWillShow:(NSNotification *)notification {
    if (self.isFullScreen) {
        return;
    }
    WS(weakSelf)
    self.isLock = YES;
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:[info[UIKeyboardAnimationDurationUserInfoKey] doubleValue]
                          delay:0
                        options:([info[UIKeyboardAnimationCurveUserInfoKey] integerValue]<<16)
                     animations:^{
                         [weakSelf.commentInputView mas_updateConstraints:^(MASConstraintMaker *make) {
                             make.bottom.mas_equalTo(- kbSize.height);
                             make.height.mas_equalTo(weakSelf.commentInputView.bounds.size.height);
                         }];
                         weakSelf.inputBg.hidden = NO;
                         [weakSelf.view bringSubviewToFront:weakSelf.inputBg];
                         [weakSelf.view layoutIfNeeded];
                     }
                     completion:^(BOOL finished){
                     }];
}

- (void)keyboardWillHidden:(NSNotification *)notification {
    if (self.isFullScreen) {
        return;
    }
    WS(weakSelf)
    if ([[LYLocalData sharedInstance] BoolValueForKey:kLYAppInAssess]) {
       
        [LYLocalData sharedInstance].roomInfo.living = @(1);
    }

    if ([LYLocalData sharedInstance].roomInfo.living.integerValue == 1) {
        self.isLock = NO;
    }
    NSDictionary* info = [notification userInfo];
    [UIView animateWithDuration:[info[UIKeyboardAnimationDurationUserInfoKey] doubleValue]
                          delay:0
                        options:([info[UIKeyboardAnimationCurveUserInfoKey] integerValue]<<16)
                     animations:^{
                         [weakSelf.commentInputView mas_updateConstraints:^(MASConstraintMaker *make) {
                             make.bottom.mas_equalTo(125);
                             make.height.mas_equalTo(self.commentInputView.bounds.size.height);
                         }];
                         weakSelf.commentInputView.placeHolder = @"发表互动";
                         weakSelf.inputBg.hidden = YES;
                         [weakSelf.view layoutIfNeeded];
                     }
                     completion:nil];
}

#pragma mark ----- LYInputViewDelegate
- (void)sendInputViewText:(NSString *)text {
    
    [self speakWithText:text];
   
}

- (void)speakWithText:(NSString *)text {
    WS(weakSelf)
    if (![self.commentInputView.sendBtn.titleLabel.text isEqualToString:@"发送"]) {
        return;
    }
    if ([LYUtil isNilOrEmpty:text]) {
        [LYUtil showSuccessHUD:@"内容不能为空" AddedTo:MAIN_WINDOW interval:1.5];
        return;
    }
    [self.commentInputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-49);
        make.height.mas_equalTo(120);
    }];
    [self.view layoutIfNeeded];
    NSString *content = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (content.length > 200) {
        [LYUtil showFailedHUD:@"输入内容不能超过200字" AddedTo:self.view interval:2.0];
        return;
    }
    self.inputBg.hidden = YES;
    if (content.length) {
        [self.commentVC makeStatementWithId:self.toChatId content:content successBlock:^(BOOL success) {
            if (success) {
                
                [[SensorsAnalyticsSDK sharedInstance] track:@"LivingComment"
                                             withProperties:@{
                                                              @"ly_living_type" :[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_type],
                                                              @"ly_comment_succeed":@(YES),
                                                              @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                              }];

                weakSelf.toChatId = @0;
                [weakSelf.commentInputView.inputView resignFirstResponder];
                weakSelf.stateMentCountTime = kStatementTotalTime;
                [self.commentInputView.sendBtn setTitle:[NSString stringWithFormat:@"%lds",(long)self.stateMentCountTime] forState:UIControlStateNormal];
                [weakSelf _startStatementTimer];
                weakSelf.commentInputView.sendBtn.enabled = NO;
            } else {
              
                [[SensorsAnalyticsSDK sharedInstance] track:@"LivingComment"
                                             withProperties:@{
                                                              @"ly_living_type" :[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_type],
                                                              @"ly_comment_succeed":@(NO),
                                                              @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                              }];
            }
        }];
    }
}

- (void)textViewDidChange:(UITextView *)textView {
    WS(weakSelf)
    [self.commentInputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(weakSelf.commentInputView.bounds.size.height);
    }];
    [self.view layoutIfNeeded];
}

- (BOOL)textViewBeginEditing:(UITextView *)textView {
    if (self.isFullScreen) {
        return NO;
    }
    
    if (![LYLocalData sharedInstance].isUserLogined) {
        [LYUtil showFailedHUD:@"还未登录,请先登录" AddedTo:MAIN_WINDOW interval:1.5];
       
        [LYLocalData sharedInstance].isFromVideoPageLogin = YES;
       
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [LYLoginNewController taskAfterLogin:^{
                
                [LYLocalData sharedInstance].isFromVideoPageLogin = NO;
                
                [[SensorsAnalyticsSDK sharedInstance] track:@"SignUp"
                                             withProperties:@{
                                                              @"ly_register_succeed":@(YES),
                                                              @"ly_register_source":@"视频互动",
                                                              }];
            }];
            
        });
        return NO;
    }

    return YES;
}

#pragma mark ----- Event reponse

/**
 将以前的点赞

 @param sender <#sender description#>
 */
- (IBAction)likeAction:(id)sender {
    
    WS(weakSelf)
    LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
    LYShareSetView *shareSetView = [LYShareSetView viewWithXib];
    [shareSetView showInWindowType:LYShareViewNoFont];
    self.shareSetView = shareSetView;
    [shareSetView prepareView];
    shareSetView.typeBlock = ^(NSInteger type) {
        shareModel.channel = type;
        [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:type shareUrl:shareModel.shareUrl presentedController:self completBlock:^(id result, NSError *error) {
            
            if (error == nil) {
                [LYLocalData sharedInstance].ly_forward_position = @"视频右上角";
                [LYUtil showSuccessHUD:@"分享成功" AddedTo:MAIN_WINDOW interval:1.5];
                [weakSelf shareDoneType:type shareDict:@{@"shareUrl":shareModel.shareUrl,}];
            }
        }];
    };
}

- (void)_audioVideoChange:(UIButton *)button {
    
    self.isMovieViewHidden = YES;
    [self _moviePlayerViewTap];

    if (button.selected) {
        [self.moviePlayer.moviePlayerView addSubview:self.indicator];
        [self.moviePlayer setDefinition:VHallMovieDefinitionUHD];
        self.audioView.hidden = YES;
        [LYLocalData sharedInstance].isAudio = NO;
        [LYVideoInstance sharedInstance].isAudio = NO;
        [LYLocalData sharedInstance].isVideo = YES;
        [LYVideoInstance sharedInstance].isVideo = YES;
        [LYLocalData sharedInstance].ly_living_type = @"视频";
    } else {
        [self.moviePlayer.moviePlayerView addSubview:self.indicator];
        [self.moviePlayer setDefinition:VHallMovieDefinitionAudio];
        self.audioView.hidden = NO;
        [LYLocalData sharedInstance].isAudio = YES;
        [LYVideoInstance sharedInstance].isAudio = YES;
        [LYLocalData sharedInstance].isVideo = NO;
        [LYVideoInstance sharedInstance].isVideo = NO;
        [LYLocalData sharedInstance].ly_living_type = @"音频";
    }
    button.selected = !button.selected;
}
- (void)_rotateScreenAction {
    ScreenRotateToPortrait(UIInterfaceOrientationLandscapeRight);
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)expandNotifyView:(UITapGestureRecognizer *)tapGesture {
    CGFloat labelHeight = self.notifyLabelHeight;
    if (labelHeight < 20)   return;        
    if (!self.isNotifyExpand) {
        self.notifyView.y = self.buttonView.y + kButtonViewHeight;
        self.notifyView.size = CGSizeMake(SCREEN_WIDTH, kNotifyViewHeight + labelHeight - 10);
        self.notifyLabel.height = labelHeight;
    } else {
        self.notifyView.y = self.buttonView.y + kButtonViewHeight;
        self.notifyView.size = CGSizeMake(SCREEN_WIDTH, kNotifyViewHeight);
        self.notifyLabel.height = 14;
    }
    self.isNotifyExpand = !self.isNotifyExpand;
    
}

- (void)replayAction:(NSNotification *)notifycation {
    if (self.isFullScreen) return;
    LYCommentModel *model = notifycation.userInfo[@"model"];
    self.toChatId = model.oid;
    [self.commentInputView.inputView becomeFirstResponder];
    self.inputBg.hidden = NO;
    [self.view bringSubviewToFront:self.inputBg];
    NSString *str = [NSString stringWithFormat:@"回复%@",model.show.user.nickname];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor blackColor]
                          range:NSMakeRange(2, model.show.user.nickname.length)];
    self.commentInputView.placeHolderLabel.attributedText = attributedStr;
}

- (void)touchBGView:(UITapGestureRecognizer *)ges {
   
    [self.commentInputView.inputView becomeFirstResponder];
    if ([self.commentInputView.inputView isFirstResponder]) {
        [self.commentInputView.inputView resignFirstResponder];
    }
    self.inputBg.hidden = YES;
    [self.view sendSubviewToBack:self.inputBg];
    [self.commentInputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(125);
        make.height.mas_equalTo(self.commentInputView.bounds.size.height);
    }];
}

- (void)networkViaWWANAction {
    self.unWifiView.hidden = NO;
    [self.moviePlayer stopPlay];
}

- (void)appEnterBackground {
    
    if (!self.isWatchPlayBack) {
        self.isEnterBack = YES;
        if (self.isPlaying && [LYLocalData sharedInstance].isVideo) {
            [self.moviePlayer stopPlay];
            self.isPlaying = NO;
        }
        [self _stopClickTimer];
        [self _stopStatementTimer];
        if ([LYLocalData sharedInstance].isVideo) {
            [self.moviePlayer destroyMoivePlayer];
            [[LYVideoInstance sharedInstance].moviePlayer destroyMoivePlayer];
            WS(weakSelf)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.moviePlayer.moviePlayerView removeFromSuperview];
               
                [weakSelf.rotateButton removeFromSuperview];
                [weakSelf.audioButton removeFromSuperview];
                [weakSelf.definitionView removeFromSuperview];
                [weakSelf.bottomImageview removeFromSuperview];

                _moviePlayer = nil;
                [LYVideoInstance sharedInstance].moviePlayer = nil;
            });
        }

    }
    
}

- (void)appEnterForeground {
    
    UIViewController *viewController = self.navigationController.viewControllers.lastObject;
    if (![viewController isKindOfClass:[LYVedioLiveController class]]) return;
    
    if (!self.isWatchPlayBack) {
        self.isEnterBack = NO;
        [self _getLivingStatus];
        
        WS(weakSelf)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.view addSubview:weakSelf.moviePlayer.moviePlayerView];
            [weakSelf.view bringSubviewToFront:weakSelf.moviePlayer.moviePlayerView];
            [weakSelf.view insertSubview:weakSelf.navView aboveSubview:weakSelf.moviePlayer.moviePlayerView];
            
            [weakSelf.view insertSubview:weakSelf.rotateButton aboveSubview:weakSelf.moviePlayer.moviePlayerView];
            [weakSelf.view insertSubview:weakSelf.audioButton aboveSubview:weakSelf.moviePlayer.moviePlayerView];
            [weakSelf.view insertSubview:weakSelf.definitionView aboveSubview:weakSelf.moviePlayer.moviePlayerView];
            [weakSelf.view insertSubview:weakSelf.bottomImageview aboveSubview:weakSelf.moviePlayer.moviePlayerView];

            [_moviePlayer.moviePlayerView addSubview:weakSelf.fullOverView];
            [_moviePlayer.moviePlayerView addSubview:weakSelf.finishedView];
            [_moviePlayer.moviePlayerView addSubview:weakSelf.unWifiView];
            [_moviePlayer.moviePlayerView addSubview:weakSelf.audioView];
        });
    }
}

//进入全屏
-(void)begainFullScreen
{
    LYAppDelegate *appDelegate = (LYAppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
    LYAppDelegate *appDelegate = (LYAppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = NO;
    
    //强制归正：
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

- (void)livingStatusChange {
  
    if ([LYLocalData sharedInstance].isViaWWAN == YES)   return;
    if (self.isWatchPlayBack) {
        return;
    }
    [self _getLivingStatus];
    
}

-(void)zanNumChange:(NSNotification *)notifycation {
   
    NSString *zanNumStr = notifycation.userInfo[@"zan_num"];
    self.videoBottomView.numLabel.text = [NSString stringWithFormat:@"%@",zanNumStr];
    if (!zanNumStr.integerValue) {
        self.videoBottomView.numLabel.text = @"点赞";
    }
    [LYLocalData sharedInstance].roomInfo.zan_num =  [NSNumber numberWithInteger:zanNumStr.integerValue];
}

#pragma mark ----- Private methods
- (void)_startMoviePlayer {
    
    if ([LYUtil hasNetwork]) {
        [self.noVideoView removeFromSuperview];
        self.isFinishedVideo = NO;
        
        NSString *idString;
        idString = [NSString stringWithFormat:@"%ld",(long)[LYLocalData sharedInstance].roomInfo.vhall.integerValue];
       
        if ([[LYLocalData sharedInstance] BoolValueForKey:kLYAppInAssess]) {
        
            idString = [NSString stringWithFormat:@"507339787"];
        }
        NSString *nameString = [NSString stringWithFormat:@"iOS_user_%@",[LYLocalData sharedInstance].uuId];
        NSString *emailString = [NSString stringWithFormat:@"%@@iOS.lanyife.com",[LYLocalData sharedInstance].uuId];
        NSDictionary *param = @{ @"id"               :idString,
                                 @"name"             :nameString,
                                 @"email"            :emailString
                                 };
        [self.moviePlayer startPlay:param];
        
        self.moviePlayer.moviePlayerView.backgroundColor = [UIColor colorWithHexString:@"#333333"];
        [LYUtil showProgressHUDAddedToVideoView:self.moviePlayer.moviePlayerView];
        self.isPlaying = YES;
        if ([LYLocalData sharedInstance].isAudio) {
            [self.moviePlayer.moviePlayerView addSubview:self.indicator];
            [self.moviePlayer setDefinition:VHallMovieDefinitionAudio];
            self.audioView.hidden = NO;
            self.audioButton.selected = YES;
        } else {
            [self.moviePlayer setDefinition:self.definition];
            self.audioView.hidden = YES;
            self.audioButton.selected = NO;
        }

    } else {
        [LYUtil showFailedHUD:@"暂无网络，请检查后重试～" AddedTo:self.view interval:1.5];
    }
}

- (void)_destoryMoivePlayer {
    [self.moviePlayer destroyMoivePlayer];
}

- (void)_orientationChanged {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortraitUpsideDown:
        case UIInterfaceOrientationPortrait:{
            if (!self.isLock)
            {
                [self _toSmallScreen];
                if (self.buttonViewType == IntroduceButtonSelected) {
                    self.scrollView.contentOffset = CGPointMake(0, 0);
                    self.buttonView.buttonType = IntroduceButtonSelected;
                
                } else if (self.buttonViewType == CommentButtonSelected) {
                    self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH * 1, 0);
                    self.buttonView.buttonType = CommentButtonSelected;
                }
            };
        }
            break;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:{
            [self setNeedsStatusBarAppearanceUpdate];
            if (!self.isLock)  [self _toFullScreen];
        }
            break;
        default:
            break;
    }
}

- (void)_toSmallScreen {
    
    if (self.isWatchPlayBack) {
        CGRect frame = CGRectZero;
        if (isIPhoneX) {
            frame = CGRectMake(0, 44, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        } else {
            frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        }
        self.backgroundView.frame = frame;
        self.watchPlayBackVC.view.frame = self.backgroundView.bounds;
        [self.view bringSubviewToFront:self.backgroundView];
        return;
    }
    

    
    
    self.isFullScreen = NO;
    [self.fullOverView.fullScreenInputView.inputView resignFirstResponder];
    self.isMovieViewHidden = YES;
    self.commentVC.bottomView.hidden = NO;
    self.noVideoView.nvRotateBtn.hidden = YES;
    [self.tabBarController.view sendSubviewToBack:self.tabBarController.tabBar];
    [self _moviePlayerViewTap];
    self.view.width = SCREEN_WIDTH;
    CGRect frame = CGRectZero;
    if (isIPhoneX) {
        frame = CGRectMake(0, 44, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
    } else {
        frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
    }
    self.tabBarController.tabBar.hidden = NO;
    [self.view insertSubview:self.navView aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.rotateButton aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.audioButton aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.definitionView aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view insertSubview:self.bottomImageview aboveSubview:self.moviePlayer.moviePlayerView];

    self.commentVC.isFullScrComment = NO;
    [self.commentVC.commentTable reloadData];
    self.moviePlayer.moviePlayerView.frame = frame;
    [self.indicator setCenter:CGPointMake(self.moviePlayer.moviePlayerView.frame.size.width / 2.0, self.moviePlayer.moviePlayerView.frame.size.height / 2.0)];

    self.unWifiView.bounds = _moviePlayer.moviePlayerView.frame;
    self.unWifiView.origin = CGPointMake(0, 0);
    self.unWifiView.unWiFiViewBottom.constant = 10;
    if (isIPhoneX) {
        self.buttonView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + 44, SCREEN_WIDTH, kButtonViewHeight);
    } else {
        self.buttonView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate(), SCREEN_WIDTH, kButtonViewHeight);
    }
    self.notifyView.frame = CGRectMake(0, self.buttonView.y + kButtonViewHeight , ScreenWidth, kNotifyViewHeight);
    _rotateButton.frame = CGRectMake(SCREEN_WIDTH - 51, self.buttonView.y - 51, 39, 39);
    _audioButton.frame = CGRectMake(SCREEN_WIDTH - 105, self.buttonView.y - 51, 39, 39);
    _definitionView.frame = CGRectMake(SCREEN_WIDTH - 105 - 20 - 54, self.buttonView.y - 160, 54, 141);
    _bottomImageview.frame = CGRectMake(0, self.buttonView.y - 60, SCREEN_WIDTH, 60);
    CGFloat contentHeight = SCREEN_HEIGHT - kTabbarHeight - (MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight);
    if ([LYUtil isNilOrEmpty:[LYLocalData sharedInstance].roomInfo.announce] || [[LYLocalData sharedInstance].roomInfo.announce isEqualToString:@"暂无公告"]) {
        self.notifyView.hidden = YES;
        if (isIPhoneX) {
            self.scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + 44, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight + 44) );
        } else {
            self.scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight) );
        }
    } else {
        self.notifyView.hidden = NO;
        if (isIPhoneX) {
            self.scrollView.frame = CGRectMake(0, self.notifyView.y + kNotifyViewHeight, ScreenWidth, contentHeight - 44);
        } else {
            self.scrollView.frame = CGRectMake(0, self.notifyView.y + kNotifyViewHeight, ScreenWidth, contentHeight);
        }
    }
    self.noVideoView.frame = self.moviePlayer.moviePlayerView.bounds;
    [self.noVideoView removeGestureRecognizer:self.fullOverView.showTwoTap];
    self.fullOverView.alpha = 0;
   
    [self.fullOverView stopRefreshCommentTimer];
    [self.commentVC beginRefreshCommentTimer];
    
    if (self.definition == VHallMovieDefinitionHD) {
        self.definitionView.viewType = DefinitionViewHighClear;
    } else if (self.definition == VHallMovieDefinitionSD) {
        self.definitionView.viewType = DefinitionViewNormalClear;
    } else if (self.definition == VHallMovieDefinitionUHD) {
        self.definitionView.viewType = DefinitionViewMaxClear;
    } else if (self.definition == VHallMovieDefinitionOrigin) {
        self.definitionView.viewType = DefinitionViewOriginClear;
    }
    if (self.isNotifyExpand) {
        [self expandNotifyView:nil];
    }
}

- (void)_toFullScreen {
    
    if (self.isWatchPlayBack) {
        self.backgroundView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        self.watchPlayBackVC.view.frame = self.backgroundView.bounds;
        [self.view bringSubviewToFront:self.backgroundView];
        return;
    }
    
    self.fullOverView.alpha = 1;
    [self.fullOverView beginRefreshCommentTimer];
    [self.commentVC stopRefreshCommentTimer];
    
    self.isFullScreen = YES;
    self.inputBg.hidden = YES;
    self.commentVC.bottomView.hidden = YES;
    CGRect frame = CGRectZero;
    [[UIApplication sharedApplication] setStatusBarHidden: NO];
    frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.tabBarController.tabBar.hidden = YES;
    [self.view insertSubview:self.navView aboveSubview:self.moviePlayer.moviePlayerView];
    [self.view bringSubviewToFront:self.moviePlayer.moviePlayerView];
    _moviePlayer.moviePlayerView.frame = frame;
    [self.indicator setCenter:CGPointMake(self.moviePlayer.moviePlayerView.frame.size.width / 2.0, self.moviePlayer.moviePlayerView.frame.size.height / 2.0)];

    _unWifiView.bounds = _moviePlayer.moviePlayerView.frame;
    _unWifiView.origin = CGPointMake(0, 0);
    self.unWifiView.unWiFiViewBottom.constant = 98;

    self.fullOverView.frame = frame;
    self.fullOverView.noVideoView = self.noVideoView;
    self.fullOverView.definition = self.definition;
    self.fullOverView.isAudio = [LYLocalData sharedInstance].isAudio;
    self.fullOverView.isNoVideo = self.isNoVideoData;
    self.fullOverView.definitionArray = [LYVideoInstance sharedInstance].definitionArray;
    self.fullOverView.screenType = FullScreenTypeShow;
    self.fullOverView.model = [LYLocalData sharedInstance].roomInfo;
    [_moviePlayer.moviePlayerView addSubview:self.fullOverView];
    self.fullOverView.commentVC.isFullScrComment = YES;
    [self.fullOverView.commentVC.commentTable reloadData];
    if (self.isNoVideoData) {
        self.noVideoView.frame = self.moviePlayer.moviePlayerView.bounds;
        self.noVideoView.nvRotateBtn.hidden = NO;
        [_moviePlayer.moviePlayerView insertSubview:self.noVideoView aboveSubview:self.fullOverView];

    }
    
    [_moviePlayer.moviePlayerView insertSubview:self.unWifiView aboveSubview:self.fullOverView];
    if (self.isNotifyExpand) {
        [self expandNotifyView:nil];
    }
}

- (void)_moviePlayerViewTap {
    WS(weakSelf)
    
    if (!self.isMovieViewHidden) {
        [UIView animateWithDuration:kAnimationTime animations:^{
            weakSelf.navView.hidden = YES;
            if (weakSelf.isFinishedVideo) return ;
            weakSelf.rotateButton.hidden = YES;
            weakSelf.audioButton.hidden = YES;
            weakSelf.definitionView.hidden = YES;
            weakSelf.bottomImageview.hidden = YES;
            if (isIPhoneX) {
                [[UIApplication sharedApplication] setStatusBarHidden:NO];
            } else {
                [[UIApplication sharedApplication] setStatusBarHidden:YES];

            }
        } completion:^(BOOL finished) {
        }];
    } else {
        [UIView animateWithDuration:kAnimationTime animations:^{
            weakSelf.navView.hidden = NO;
            if (weakSelf.isFinishedVideo) return ;
            weakSelf.rotateButton.hidden = NO;
            weakSelf.audioButton.hidden = NO;
            weakSelf.definitionView.hidden = NO;
            weakSelf.bottomImageview.hidden = NO;
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
        } completion:^(BOOL finished) {
        }];
    }
    self.isMovieViewHidden = !self.isMovieViewHidden;
    [self _resetTimer];
}

- (void)_resetTimer {
    if (nil ==_clickTimer) {
        _clickTimer = [NSTimer scheduledTimerWithTimeInterval:kNavViewAnimationTime
                                                       target:self
                                                     selector:@selector(_hideTopView)
                                                     userInfo:nil
                                                      repeats:NO];
        [[NSRunLoop mainRunLoop] addTimer:self.clickTimer forMode:NSRunLoopCommonModes];
    } else {
        if (fabs([self.clickTimer.fireDate timeIntervalSinceNow]) < kNavViewAnimationTime)
            [self.clickTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kNavViewAnimationTime]];
    }
}

- (void)_stopClickTimer {
    if (self.clickTimer) {
        [self.clickTimer invalidate];
        self.clickTimer = nil;
    }
}

- (void)_hideTopView {
    if (!self.inThisPage) return;
    WS(weakSelf)
    [self _stopClickTimer];
    if (self.isFinishedVideo) {
        self.rotateButton.hidden = YES;
        self.audioButton.hidden = YES;
        self.definitionView.hidden = YES;
        self.bottomImageview.hidden = YES;
        return;
    } else {
        self.rotateButton.hidden = NO;
        self.audioButton.hidden = NO;
        self.definitionView.hidden = NO;
        self.bottomImageview.hidden = NO;
    }
    [UIView animateWithDuration:kAnimationTime animations:^{
        weakSelf.navView.hidden = YES;
        weakSelf.rotateButton.hidden = YES;
        weakSelf.audioButton.hidden = YES;
        weakSelf.definitionView.hidden = YES;
        weakSelf.bottomImageview.hidden = YES;
        if (!weakSelf.isFullScreen) {
            
            if (isIPhoneX) {
                [[UIApplication sharedApplication] setStatusBarHidden:NO];
            } else {
                [[UIApplication sharedApplication] setStatusBarHidden:YES];
            }
        }
    } completion:^(BOOL finished) {
    }];
    self.isMovieViewHidden = YES;
}

- (void)_startStatementTimer {
    [self _stopStatementTimer];
    if (nil == _stateMentTimer) {
        _stateMentTimer = [NSTimer scheduledTimerWithTimeInterval:kStatementIntervalTime
                                                           target:self
                                                         selector:@selector(_stateMentEnable)
                                                         userInfo:nil
                                                          repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.stateMentTimer forMode:NSRunLoopCommonModes];
    } else {
        if (fabs([self.stateMentTimer.fireDate timeIntervalSinceNow]) < kStatementIntervalTime)
            [self.stateMentTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kStatementIntervalTime]];
    }
}

- (void)_stopStatementTimer {
    if (self.stateMentTimer) {
        [self.stateMentTimer invalidate];
        self.stateMentTimer = nil;
    }
}

- (void)_stateMentEnable {
    
    if (self.stateMentCountTime < 0)         self.stateMentCountTime = 0;
    [self.commentInputView.sendBtn setTitle:[NSString stringWithFormat:@"%lds",(long)self.stateMentCountTime] forState:UIControlStateNormal];
    self.stateMentCountTime --;
    if (self.stateMentCountTime <= 0) {
        [self.commentInputView.sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [self _stopStatementTimer];
        self.commentInputView.sendBtn.enabled = YES;
        self.stateMentCountTime = 0;
    }
}

- (NSString *)_returnCurrentTime {
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}

- (void)toPlayblackVC {
    
    WatchPlayBackViewController *vc = [WatchPlayBackViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];    
}

#pragma mark - ******** 设置子controller 快捷键为mark
- (void)_addChildViewController {
    WS(weakSelf)
    
    // 时刻表
    self.introduceVC = [[LYIntroduceController alloc] initWithNibName:@"LYIntroduceController" bundle:nil];
    self.introduceVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.scrollView.height);
    self.introduceVC.introduceBlock = ^(LYIntroduceModel *model) {
        [weakSelf _loadRoomInfo:model];
    };
    
    //回放
    self.introduceVC.playBackBlock = ^(LYRoomListModel *model) {
        weakSelf.isLock = NO;
        [weakSelf.moviePlayer pausePlay];
        weakSelf.moviePlayer.moviePlayerView.hidden = YES;
        weakSelf.isWatchPlayBack = YES;
        [weakSelf.view addSubview:weakSelf.backgroundView];
        weakSelf.backgroundView.hidden = NO;
       
        [[SensorsAnalyticsSDK sharedInstance] track:@"WatchBackVideo"
                                     withProperties:@{
                                                      @"ly_video_name" :[LYUtil lySensorsString:model.actName] ,
                                                      }];

        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            model.vhallId = @"522193684";
            weakSelf.watchPlayBackVC.isVideoLivingPage = YES;
            [weakSelf.watchPlayBackVC startWatchPlayBack:model.vhallId];
        });

    };
    
    //直播
    self.introduceVC.videoLiveBlock = ^{
        
        weakSelf.isWatchPlayBack = NO;
        [weakSelf.watchPlayBackVC pauseWatchPlayBack];
        
        weakSelf.backgroundView.hidden = YES;
        weakSelf.moviePlayer.moviePlayerView.hidden = NO;
       
        [weakSelf.view addSubview:weakSelf.moviePlayer.moviePlayerView];
        [weakSelf.view bringSubviewToFront:weakSelf.moviePlayer.moviePlayerView];
        if (isIPhoneX && !self.isFullScreen) {
            weakSelf.moviePlayer.moviePlayerView.frame = CGRectMake(0, 44, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        } else if (self.isFullScreen && isIPhoneX) {
            weakSelf.moviePlayer.moviePlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        } else  {
            weakSelf.moviePlayer.moviePlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        }

        [weakSelf.view insertSubview:weakSelf.navView aboveSubview:weakSelf.moviePlayer.moviePlayerView];
        [weakSelf.view insertSubview:weakSelf.rotateButton aboveSubview:weakSelf.moviePlayer.moviePlayerView];
        [weakSelf.view insertSubview:weakSelf.audioButton aboveSubview:weakSelf.moviePlayer.moviePlayerView];
        [weakSelf.view insertSubview:weakSelf.definitionView aboveSubview:weakSelf.moviePlayer.moviePlayerView];
        [weakSelf.view insertSubview:weakSelf.bottomImageview aboveSubview:weakSelf.moviePlayer.moviePlayerView];

        
        [weakSelf _startMoviePlayer];
    };
    
    [self.scrollView addSubview:self.introduceVC.view];
    [self addChildViewController:self.introduceVC];
    
    self.commentVC = [[LYCommentController alloc] initWithNibName:@"LYCommentController" bundle:nil];
    if (isIPhoneX) {
        self.commentVC.view.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, self.scrollView.height - 49 - 34);
    } else {
        self.commentVC.view.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, self.scrollView.height - 49);
    }
    [self.scrollView addSubview:self.commentVC.view];
    [self addChildViewController:self.commentVC];
}

- (void)_addNotification {
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_orientationChanged) name:@"UIDeviceOrientationDidChangeNotification"object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkViaWWANAction) name:kNetworkStatusReachableViaWWAN object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareSuccessDone:) name:kFullScreenShareDoneNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name:kApplicationDidEnterBackground object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForeground) name:kApplicationDidEnterForeground object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(livingStatusChange) name:kWebSocketVideoLiveStatusChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zanNumChange:) name:kWebSocketVideoZanNumChange object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareSuccessDone:) name:kFullScreenShareDoneNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(joinTeam:) name:@"LYTimeTableTeacherInfoTableViewCellJoinBtnClick" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kVedioLiveControllerRemoveSmallVideoScreen object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlaySuccess) name:kLYVideoInstancePlaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlayErrorHandel) name:kLYVideoInstanceHandelError object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinishPlaying) name:kLYVideoInstanceFinishPlaying object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoBeginLoading) name:kLYVideoInstanceBeginLoading object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinishLoading) name:kLYVideoInstanceFinishLoading object:nil];
}

- (void)_initData {
    self.isNotifyExpand = NO;
    self.isMovieViewHidden = NO;
    self.isLock = NO;
    self.isNoVideoData = NO;
    self.isFullScreen = NO;
    self.isFinishedVideo = NO;
    self.toChatId = @0;
    self.definition = VHallMovieDefinitionSD;
    [LYLocalData sharedInstance].isVideo = YES;
    self.isEnterBack = NO;
    self.stateMentCountTime = kStatementTotalTime;
    [LYLocalData sharedInstance].ly_living_type = @"视频";
    [LYLocalData sharedInstance].ly_living_definition = @"标清";
    self.isWatchPlayBack = NO;
}

//轮循获取解盘状态
- (void)_getLivingStatus {
    
    WS(weakSelf)
    [self.videoLiveService getVideoLivingStatus:nil block:^(BOOL success, id object) {
        
        if (success) {
            if ([[LYLocalData sharedInstance] BoolValueForKey:kLYAppInAssess]) {
                [LYLocalData sharedInstance].roomInfo.living = @(1);
            }
            if ([LYLocalData sharedInstance].roomInfo.living.integerValue == 1) {
                if ([LYLocalData sharedInstance].isViaWWAN) {
                    [weakSelf networkViaWWANAction];
                } else {
                    [weakSelf _startMoviePlayer];
                }
                [LYLocalData sharedInstance].ly_living_access_state = @"直播中";
                [[SensorsAnalyticsSDK sharedInstance] track:@"LivingAccess"
                                             withProperties:@{
                                                              @"ly_living_access_state" : @"直播中",
                                                              @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                              @"ly_entry":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_entry],
                                                              }];
            } else {
                [weakSelf videoLiveFinished];
                [LYLocalData sharedInstance].ly_living_access_state = @"暂无直播";
                [[SensorsAnalyticsSDK sharedInstance] track:@"LivingAccess"
                                             withProperties:@{
                                                              @"ly_living_access_state" : @"暂无直播",
                                                              @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                              @"ly_entry":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_entry],
                                                              }];
            }
        } else {
//            [weakSelf videoLiveFinished];
            [weakSelf videoPlayErrorHandel];
        }
    }];
}

- (void)_setupInputView {
    [self.commentInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 120));
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(125);
    }];
    [self.inputBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.bottom.equalTo(self.commentInputView.mas_top).offset(0);
    }];
    [self.view insertSubview:self.commentInputView aboveSubview:self.inputBg];
}

- (void)videoLiveBegin {
    
    [[SensorsAnalyticsSDK sharedInstance] track:@"LivingWatch"
                                 withProperties:@{
                                                  @"ly_living_type" :[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_type],
                                                  @"ly_living_definition":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_definition],
                                                  @"ly_living_succeed":@"成功",
                                                  @"ly_living_change_time":[LYUtil lySensorsString:[self _returnCurrentTime]],
                                                  @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                  }];

    WS(weakSelf)
    [self.noVideoView removeFromSuperview];
    [self.finishedView removeFromSuperview];
    self.isMovieViewHidden = YES;
    [self _moviePlayerViewTap];
    CGFloat contentHeight = SCREEN_HEIGHT - kTabbarHeight - (MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight);
    if (isIPhoneX && !self.isFullScreen) {
        weakSelf.moviePlayer.moviePlayerView.frame = CGRectMake(0, 44, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
    } else if (self.isFullScreen && isIPhoneX) {
       weakSelf.moviePlayer.moviePlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    } else  {
        weakSelf.moviePlayer.moviePlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
    }
    if (isIPhoneX) {
        weakSelf.buttonView.frame =  CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + 44, SCREEN_WIDTH, kButtonViewHeight);
    } else {
        weakSelf.buttonView.frame =  CGRectMake(0, MoviePlayerViewHeightWithScreenRate(), SCREEN_WIDTH, kButtonViewHeight);
    }
    weakSelf.notifyView.frame = CGRectMake(0, weakSelf.buttonView.y + kButtonViewHeight , ScreenWidth, kNotifyViewHeight);
    if ([LYUtil isNilOrEmpty:[LYLocalData sharedInstance].roomInfo.announce] ||[[LYLocalData sharedInstance].roomInfo.announce isEqualToString:@"暂无公告"]) {
        if (isIPhoneX) {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + 44, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight + 44) );
        } else {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight) );
        }
    } else {
        if (isIPhoneX) {
            self.scrollView.frame = CGRectMake(0, self.notifyView.y + kNotifyViewHeight, ScreenWidth, contentHeight - 44);
        } else {
            self.scrollView.frame = CGRectMake(0, self.notifyView.y + kNotifyViewHeight, ScreenWidth, contentHeight);
        }
    }
    _rotateButton.frame = CGRectMake(SCREEN_WIDTH - 51, self.buttonView.y - 51, 39, 39);
    _audioButton.frame = CGRectMake(SCREEN_WIDTH - 105, self.buttonView.y - 51, 39, 39);
    _definitionView.frame = CGRectMake(SCREEN_WIDTH - 105 - 20 - 54, self.buttonView.y - 160, 54, 141);
    _bottomImageview.frame = CGRectMake(0, self.buttonView.y - 60, SCREEN_WIDTH, 60);
    [weakSelf.finishedView removeFromSuperview];
    weakSelf.isLock = NO;

    [self.moviePlayer.moviePlayerView addSubview:self.indicator];
    [self.moviePlayer setDefinition:self.definition];
    self.buttonView.buttonType = LikeButtonSelected;
    self.rotateButton.hidden = NO;
    self.audioButton.hidden = NO;
    self.definitionView.hidden = NO;
    self.bottomImageview.hidden = NO;
    self.likeBtn.hidden = NO;
    self.likeNumLab.hidden = NO;
    if (self.isNotifyExpand) {
        [self expandNotifyView:nil];
    }
    
    [self begainFullScreen];

}

- (void)videoLiveFinished {
    WS(weakSelf)
    CGFloat contentHeight = SCREEN_HEIGHT - kTabbarHeight - (MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight);
    if ( [LYUtil isNilOrEmpty:[LYLocalData sharedInstance].roomInfo.announce] ||[[LYLocalData sharedInstance].roomInfo.announce isEqualToString:@"暂无公告"]) {
            self.notifyView.hidden = YES;
        if (isIPhoneX) {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate()+ kButtonViewHeight + 44, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight + 44) );
        } else {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate()+ kButtonViewHeight, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight) );
        }
    } else {
            self.notifyView.hidden = NO;
        if (isIPhoneX) {
            weakSelf.scrollView.frame = CGRectMake(0, weakSelf.notifyView.y + kNotifyViewHeight + 44, ScreenWidth, contentHeight - 44);
        } else {
            weakSelf.scrollView.frame = CGRectMake(0, weakSelf.notifyView.y + kNotifyViewHeight, ScreenWidth, contentHeight);
        }
    }
    weakSelf.isLock = YES;
    
    _finishedView = nil;
    [_finishedView removeFromSuperview];
    [weakSelf.moviePlayer.moviePlayerView addSubview:weakSelf.finishedView];
    weakSelf.finishedView.hidden = NO;
    weakSelf.finishedView.frame = weakSelf.moviePlayer.moviePlayerView.bounds;
    [weakSelf.moviePlayer.moviePlayerView bringSubviewToFront:weakSelf.finishedView];
    [self.finishedImage sd_setImageWithURL:[NSURL URLWithString:[LYLocalData sharedInstance].roomInfo.offline_img_url] placeholderImage:[UIImage imageNamed:@"video_restDefault"]];
    self.buttonView.buttonType = VideoFinished;
    self.isFinishedVideo = YES;
    self.rotateButton.hidden = YES;
    self.audioButton.hidden = YES;
    self.definitionView.hidden = YES;
    self.bottomImageview.hidden = YES;
    self.likeBtn.hidden = YES;
    self.likeNumLab.hidden = YES;
    [LYLocalData sharedInstance].roomInfo.living = @(0);
    [self endFullScreen];
}

- (void)_loadRoomInfo:(LYIntroduceModel *)model {
    
    _notifyLabel.text = model.announce;  
    self.buttonView.model = model;
    self.videoBottomView.numLabel.text = [NSString stringWithFormat:@"%ld",(long)model.zan_num.integerValue];
    if (!model.zan_num.integerValue) {
        self.videoBottomView.numLabel.text = @"点赞";
    }

    self.notifyLabelHeight = [LYUtil sizeWithText:model.announce font:[UIFont systemFontOfSize:kNotifyLabelFontSize] withWidth:SCREEN_WIDTH - 60].height;
    self.videoTitle.text = model.name;
    if ([LYUtil isNilOrEmpty:model.announce] ||[model.announce isEqualToString:@"暂无公告"]) {
        self.notifyView.hidden = YES;
        if (isIPhoneX) {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + 44, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight + 44) );
        } else {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight) );
        }
    } else {
        self.notifyView.hidden = NO;
        if (isIPhoneX) {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight + 44, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight + kNotifyViewHeight + 44) );
        } else {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight, SCREEN_WIDTH, SCREEN_HEIGHT -(MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kTabbarHeight + kNotifyViewHeight));
        }
    }
}

#pragma mark ----- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x == 0) {
        self.buttonView.buttonType = IntroduceButtonSelected;
        self.commentInputView.hidden = YES;
        self.videoBottomView.hidden = YES;
        self.buttonViewType = IntroduceButtonSelected;
    }
    else if (scrollView.contentOffset.x == ScreenWidth ) {
        self.buttonView.buttonType = CommentButtonSelected;
        self.commentInputView.hidden = NO;
        self.videoBottomView.hidden = NO;
        self.buttonViewType = CommentButtonSelected;
    }
}

#pragma mark ----- getters and setters
- (VHallMoviePlayer *)moviePlayer {         
    if (nil == _moviePlayer) {
        _moviePlayer = [LYVideoInstance sharedInstance].moviePlayer;  // [[VHallMoviePlayer alloc] initWithDelegate:self];
        _moviePlayer.movieScalingMode = kRTMPMovieScalingModeAspectFit;
        _moviePlayer.reConnectTimes = kReConnectTimes;
        if (isIPhoneX) {
            _moviePlayer.moviePlayerView.frame = CGRectMake(0, 44, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        } else {
            _moviePlayer.moviePlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        }
        _moviePlayer.moviePlayerView.backgroundColor = [UIColor colorWithHexString:@"#333333"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_moviePlayerViewTap)];
        _moviePlayer.moviePlayerView.userInteractionEnabled = YES;
        [_moviePlayer.moviePlayerView addGestureRecognizer:tap];
        [_moviePlayer.moviePlayerView addSubview:self.unWifiView];
        [_moviePlayer.moviePlayerView addSubview:self.audioView];
        
           }
    return _moviePlayer;
}



- (UIView *)notifyView {
    if (nil == _notifyView) {
        _notifyView = [[UIView alloc] init];
        _notifyView.frame = CGRectMake(0, self.buttonView.y + kButtonViewHeight, SCREEN_WIDTH, kNotifyViewHeight);
        _notifyView.backgroundColor = [UIColor colorWithHexString:@"#bbc6dc"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(expandNotifyView:)];
        _notifyView.hidden = YES;
        _notifyView.userInteractionEnabled = YES;
        _notifyView.clipsToBounds = YES;
        [_notifyView addGestureRecognizer:tap];
        UIImageView *imageV = [[UIImageView alloc] init];
        imageV.frame = CGRectMake(10, 9, 28, 13);
        imageV.image = [UIImage imageNamed:@"videoLive_notify"];
        [_notifyView addSubview:imageV];
        _notifyLabel = [[UILabel alloc] init];
        _notifyLabel.frame = CGRectMake(45, 8, SCREEN_WIDTH - 60, 14);
        _notifyLabel.font = [UIFont systemFontOfSize:13];
        _notifyLabel.textColor = [UIColor whiteColor];
        _notifyLabel.numberOfLines = 0;
        [_notifyView addSubview:_notifyLabel];
    }
    return _notifyView;
}

- (UIScrollView *)scrollView {
    CGFloat contentHeight = SCREEN_HEIGHT - kTabbarHeight - (MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight);
    if (nil == _scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        if (isIPhoneX) {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight + 44, SCREEN_WIDTH, contentHeight - 44);
            _scrollView.contentSize = CGSizeMake(2 * SCREEN_WIDTH, contentHeight - 44);
        } else {
            _scrollView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + kButtonViewHeight + kNotifyViewHeight, SCREEN_WIDTH, contentHeight);
            _scrollView.contentSize = CGSizeMake(2 * SCREEN_WIDTH, contentHeight);
        }
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = [UIColor whiteColor];
    }
    return _scrollView;
}

- (LYVideoButtonView *)buttonView {
    WS(weakSelf)
    if (nil == _buttonView) {
        _buttonView = [LYVideoButtonView viewWithXib];
        _buttonView.buttonType = IntroduceButtonSelected;
        weakSelf.buttonViewType = TeacherButtonSelected;
        if (isIPhoneX) {
            _buttonView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate() + 44, SCREEN_WIDTH, kButtonViewHeight);
        } else {
            _buttonView.frame = CGRectMake(0, MoviePlayerViewHeightWithScreenRate(), SCREEN_WIDTH, kButtonViewHeight);
        }
//        _buttonView.model = [LYLocalData sharedInstance].roomInfo;
        __block LYVideoButtonView *btnView = _buttonView;
        _buttonView.introduceBlock = ^() {
            weakSelf.scrollView.contentOffset = CGPointMake(0, 0);
            btnView.buttonType = IntroduceButtonSelected;
            weakSelf.buttonViewType = IntroduceButtonSelected;
        };
        _buttonView.commentBlock = ^() {
            weakSelf.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH * 1, 0);
            btnView.buttonType = CommentButtonSelected;
            weakSelf.buttonViewType = CommentButtonSelected;
        };
        
        _buttonView.shareBlock = ^() {
            
            LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
            LYShareSetView *shareSetView = [LYShareSetView viewWithXib];
            [shareSetView showInWindowType:LYShareViewNoFont];
            [shareSetView prepareView];
            shareSetView.typeBlock = ^(NSInteger type) {
                shareModel.channel = type;
                [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:type shareUrl:shareModel.shareUrl presentedController:weakSelf completBlock:^(id result, NSError *error) {
                    
                    if (error == nil) {
                        [LYUtil showSuccessHUD:@"分享成功" AddedTo:MAIN_WINDOW interval:1.5];
                    }
                }];
            };

            
        };
        _buttonView.buttonType = IntroduceButtonSelected;
        _buttonView.introduceBlock();
    }
    return _buttonView;
}

#pragma mark - 分享成功后的回调
- (void)shareDoneType:(LYShareType)type shareDict:(NSDictionary *)shareDict
{
    [self.shareSetView dismiss];
    NSString *channel = @"1";
    NSString *shareType = nil;
    switch (type) {
        case LYShareQQ:
            channel = @"1";
            shareType = @"QQ";
            break;
        case LYShareWeixiSession:
            channel = @"2";
            shareType = @"微信";
            break;
        case LYSinaWeibo:
            channel = @"3";
            shareType = @"微博";
            break;
        case LYShareQQSpace:
            channel = @"4";
            shareType = @"QQ空间";
            break;
        case LYShareWeixiTimeline:
            channel = @"5";
            shareType = @"朋友圈";
            break;
        default:
            break;
    }
    [LYFuDaiView showFuDaiIfHaveWithNav:self.navigationController param:@{@"channel":channel,@"url":shareDict[@"shareUrl"]}];
    
    [[SensorsAnalyticsSDK sharedInstance] track:@"LivingForward"
                                 withProperties:@{
                                                  @"ly_living_type":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_type],
                                                  @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                  @"ly_forward_position":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_forward_position],
                                                  @"ly_forward_type":[LYUtil lySensorsString:shareType],
                                                  }];
}
#pragma mark 全屏分享成后的回调
- (void)shareSuccessDone:(NSNotification *)notify
{
    NSString *channel = notify.object;
    [LYFuDaiView showFuDaiIfHaveWithNav:self.navigationController param:@{@"channel":channel,@"url":kShareVideoUrl}];
}
- (LYVideoFullScreen *)fullOverView {
    WS(weakSelf)
    if (nil == _fullOverView) {
        _fullOverView = [LYVideoFullScreen viewWithXib];
        _fullOverView.voiceBlock      = ^(CGFloat value)                   { [VHallMoviePlayer setSysVolumeSize:value];     };
        _fullOverView.refreshBlock    = ^()                                { [weakSelf _startMoviePlayer];                  };
        _fullOverView.lockBlock       = ^(BOOL isLock)                     { weakSelf.isLock = isLock;                      };
        _fullOverView.definitionblock = ^(VHallMovieDefinition definition) { weakSelf.definition = definition;
            [weakSelf.moviePlayer.moviePlayerView addSubview:weakSelf.indicator];
            [weakSelf.moviePlayer setDefinition:definition];

            if (definition == VHallMovieDefinitionUHD) {
                [LYLocalData sharedInstance].ly_living_definition = @"超清";
            } else if (definition == VHallMovieDefinitionHD) {
                [LYLocalData sharedInstance].ly_living_definition = @"高清";
            } else if (definition == VHallMovieDefinitionSD) {
                [LYLocalData sharedInstance].ly_living_definition = @"标清";
            } else if (definition == VHallMovieDefinitionOrigin) {
                [LYLocalData sharedInstance].ly_living_definition = @"原画";
            }
            
            if (definition == VHallMovieDefinitionAudio) {
                weakSelf.audioView.hidden = NO;
                weakSelf.audioButton.selected = YES;
                [LYLocalData sharedInstance].isAudio = YES;
                [LYVideoInstance sharedInstance].isAudio = YES;
                [LYVideoInstance sharedInstance].isVideo = NO;
                [LYLocalData sharedInstance].ly_living_type = @"音频";
            } else {
                weakSelf.audioView.hidden = YES;
                weakSelf.audioButton.selected = NO;
                [LYLocalData sharedInstance].isAudio = NO;
                [LYVideoInstance sharedInstance].isAudio = NO;
                [LYVideoInstance sharedInstance].isVideo = YES;
                [LYLocalData sharedInstance].ly_living_type = @"视频";
            }
        };
        _fullOverView.likeBlock       = ^()       {
            ScreenRotateToPortrait(UIInterfaceOrientationPortrait);
            [weakSelf _toSmallScreen];
            [weakSelf userInfomationAction];
        };
        _fullOverView.likeSuccessBlock = ^(LYIntroduceModel *model) {
            if (model.is_zan.integerValue == 1) {
                weakSelf.likeNumLab.text = [NSString stringWithFormat:@"%ld",(long)model.zan_num.integerValue];
            } else {
                weakSelf.likeBtn.selected = NO;
            }
        };
        _fullOverView.backBlock       = ^()       {
            ScreenRotateToPortrait(UIInterfaceOrientationPortrait);
            [weakSelf _toSmallScreen];                                                                                      };
        
    }
    return _fullOverView;
}

- (UIView *)finishedView {
    if (nil == _finishedView) {
        _finishedView = [[UIView alloc] init];
        _finishedView.backgroundColor = [UIColor colorWithHexString:@"#bababa"];
        _finishedView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        _finishedView.hidden = YES;
        _finishedImage = [[UIImageView alloc] init];
        _finishedImage.frame = CGRectMake(0, 0, _finishedView.frame.size.width, _finishedView.frame.size.height);
        _finishedImage.contentMode = UIViewContentModeScaleAspectFill;
        _finishedImage.clipsToBounds = YES;
        [_finishedView addSubview:_finishedImage];
        
        UIView *toPlaybackView = [[UIView alloc] initWithFrame:_finishedView.bounds];
        toPlaybackView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        UIImageView *restImage = [[UIImageView alloc] initWithFrame:CGRectMake(toPlaybackView.width/2 - 119/2, 42, 119, 65)];
        restImage.image = [UIImage imageNamed:@"video_rest"];
        [toPlaybackView addSubview:restImage];
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(0, 111, SCREEN_WIDTH, 21);
        label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15.0];
        label.text = @"当前时段暂无直播，可以去视频回顾看看";
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        [toPlaybackView addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(toPlaybackView.width/2 - 100/2, 147, 100, 32);
        [button addTarget:self action:@selector(toPlayblackVC) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"前往观看" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        button.layer.borderColor = [UIColor whiteColor].CGColor;
        button.layer.borderWidth = 1.0;
        [toPlaybackView addSubview:button];
        [_finishedView addSubview:toPlaybackView];
    }
    return _finishedView;
}

- (LYVideoNoDataView *)noVideoView {
    WS(weakSelf)
    if (nil == _noVideoView) {
        _noVideoView = [LYVideoNoDataView viewWithXib];
        _noVideoView.frame = self.moviePlayer.moviePlayerView.bounds;
        _noVideoView.refreshBlock = ^() {
            
            [weakSelf _startMoviePlayer];
        };
        _noVideoView.nvRotateBlock = ^{
            ScreenRotateToPortrait(UIInterfaceOrientationPortrait);
            [weakSelf _toSmallScreen];
        };
    }
    return _noVideoView;
}

- (LYVideoUnWifiView *)unWifiView {
    WS(weakSelf)
    if (nil == _unWifiView) {
        _unWifiView = [LYVideoUnWifiView viewWithXib];
        _unWifiView.bounds = _moviePlayer.moviePlayerView.frame;
        _unWifiView.origin = CGPointMake(0, 0);
        _unWifiView.unWiFiViewBottom.constant = 10;
        _unWifiView.hidden = YES;
        _unWifiView.continuePlayBlock = ^() {
            weakSelf.unWifiView.hidden = YES;
            [weakSelf _startMoviePlayer];
            [LYLocalData sharedInstance].isViaWWAN = NO;
        };
    }
    return _unWifiView;
}

- (LYAudioView *)audioView {

    if (nil == _audioView) {
        _audioView = [LYAudioView viewWithXib];
        _audioView.bounds = _moviePlayer.moviePlayerView.frame;
        _audioView.origin = CGPointMake(0, 0);
        _audioView.hidden = YES;
    }
    return _audioView;
}

- (LYArticleInputView *)commentInputView
{
    if (nil == _commentInputView) {
        _commentInputView = [[LYArticleInputView alloc] initWithStyle:ArticleDefaultInputBarStyle];
        _commentInputView.delegate = self;
        _commentInputView.alpha = 1;
        _commentInputView.backgroundColor = [UIColor colorWithHexString:@"#d8d9db"];
        _commentInputView.keyboard.showAddBtn = NO;
        [_commentInputView.keyboard addBtnClicked:^{  }];
        _commentInputView.placeHolder = @"发表互动";
    }
    return _commentInputView;
}

-(UIView *)inputBg {
    
    if (nil == _inputBg) {
        _inputBg = [[UIView alloc] init];
        _inputBg.backgroundColor = RGBA(0, 0, 0, 0.3);
        _inputBg.hidden = YES;
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchBGView:)];
        [_inputBg addGestureRecognizer:tapGes];
    }
    return _inputBg;
}

- (UIButton *)rotateButton {
    if (nil == _rotateButton) {
        _rotateButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rotateButton.frame = CGRectMake(SCREEN_WIDTH - 51, self.buttonView.y - 51, 39, 39);
        _rotateButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [_rotateButton addTarget:self action:@selector(_rotateScreenAction) forControlEvents:UIControlEventTouchUpInside];
        [_rotateButton setImage:[UIImage imageNamed:@"video_full_change"] forState:UIControlStateNormal];
    }
    return _rotateButton;
}

- (UIButton *)audioButton {
    if (nil == _audioButton) {
        _audioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _audioButton.frame = CGRectMake(SCREEN_WIDTH - 105, self.buttonView.y - 51, 39, 39);
        _audioButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [_audioButton addTarget:self action:@selector(_audioVideoChange:) forControlEvents:UIControlEventTouchUpInside];
        [_audioButton setImage:[UIImage imageNamed:@"tingyinpin"] forState:UIControlStateNormal];
        [_audioButton setImage:[UIImage imageNamed:@"kanshipin"] forState:UIControlStateSelected];

    }
    return _audioButton;
}


- (LYVideoLiveService *)videoLiveService {
    if (nil == _videoLiveService) {
        _videoLiveService = [[LYVideoLiveService alloc] initWithDelegate:self];
    }
    return _videoLiveService;
}

- (LYDefinitionView *)definitionView {
    WS(weakSelf)
    if (nil == _definitionView) {
        _definitionView = [LYDefinitionView viewWithXib];
        _definitionView.frame = CGRectMake(SCREEN_WIDTH - 105 - 20 - 54, self.buttonView.y - 160, 54, 141);
        _definitionView.definitionblock = ^(VHallMovieDefinition definition) { weakSelf.definition = definition;
            [weakSelf.moviePlayer.moviePlayerView addSubview:weakSelf.indicator];
            [weakSelf.moviePlayer setDefinition:definition];
            if (definition == VHallMovieDefinitionUHD) {
               [LYLocalData sharedInstance].ly_living_definition = @"超清";
            } else if (definition == VHallMovieDefinitionHD) {
               [LYLocalData sharedInstance].ly_living_definition = @"高清";
            } else if (definition == VHallMovieDefinitionSD) {
               [LYLocalData sharedInstance].ly_living_definition = @"标清";
            } else if (definition == VHallMovieDefinitionOrigin) {
                [LYLocalData sharedInstance].ly_living_definition = @"原画";
            }
        };
        _definitionView.viewType = DefinitionViewNormalClear;
    }
    return _definitionView;
}

- (UIActivityIndicatorView *)indicator {

    if (nil == _indicator) {  
         _indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        _indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        _indicator.backgroundColor = [UIColor clearColor];
        _indicator.alpha = 1.0;
        _indicator.layer.cornerRadius = 6;
        _indicator.layer.masksToBounds = YES;
    }
    [_indicator setCenter:CGPointMake(self.moviePlayer.moviePlayerView.frame.size.width / 2.0, self.moviePlayer.moviePlayerView.frame.size.height / 2.0)];
    [_indicator startAnimating];
    return _indicator;
}

- (LYVideoBottomView *)videoBottomView {

    WS(weakSelf)
    if (nil == _videoBottomView) {
        _videoBottomView = [LYVideoBottomView viewWithXib];
        if (isIPhoneX) {
            _videoBottomView.frame = CGRectMake(0, SCREEN_HEIGHT - 49 - 34, SCREEN_WIDTH, 49);
        } else {
            _videoBottomView.frame = CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49);
        }
        _videoBottomView.commentBlock = ^(){
            [weakSelf.commentInputView.inputView becomeFirstResponder];
        };
        
        __block LYVideoBottomView *bottomView = _videoBottomView;
        _videoBottomView.likeBlock = ^(){
        
            [weakSelf.videoLiveService likeActionBlock:^(BOOL success) {
                if (success) {
                    
                    [[SensorsAnalyticsSDK sharedInstance] track:@"LivingLike"
                                                 withProperties:@{
                                                                  @"ly_living_type":[LYUtil lySensorsString:[LYLocalData sharedInstance].ly_living_type],
                                                                  @"ly_living_name":[LYUtil lySensorsString:[LYLocalData sharedInstance].roomInfo.name],
                                                                  }];

                    bottomView.likeButton.selected  = YES;
                    bottomView.numLabel.text = [NSString stringWithFormat:@"%ld",(long)[LYLocalData sharedInstance].roomInfo.zan_num.integerValue + 1];
                    [LYLocalData sharedInstance].roomInfo.zan_num = @([LYLocalData sharedInstance].roomInfo.zan_num.integerValue + 1);
                    [LYLocalData sharedInstance].roomInfo.is_zan = @1;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        bottomView.likeButton.selected  = NO;
                        bottomView.numLabel.text = [NSString stringWithFormat:@"%ld",(long)[LYLocalData sharedInstance].roomInfo.zan_num.integerValue];

                    });
                    
                    
                    
                } else {
                        bottomView.likeButton.selected  = NO;
                }
            }];
        };
        _videoBottomView.shareBlock = ^(){            
            LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
            LYShareSetView *shareSetView = [LYShareSetView viewWithXib];
            [shareSetView showInWindowType:LYShareViewNoFont];
            [shareSetView prepareView];
            shareSetView.typeBlock = ^(NSInteger type) {
                shareModel.channel = type;
                [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:type shareUrl:shareModel.shareUrl presentedController:weakSelf completBlock:^(id result, NSError *error) {
                    
                    if (error == nil) {
                        [LYLocalData sharedInstance].ly_forward_position = @"互动右下角";
                        [LYUtil showSuccessHUD:@"分享成功" AddedTo:MAIN_WINDOW interval:1.5];
                        [weakSelf shareDoneType:type shareDict:@{@"shareUrl":shareModel.shareUrl,}];
                    }
                }];
            };

            
        };
        _videoBottomView.hidden = YES;

    }
    return _videoBottomView;
}

- (LYVideoPlayBackView *)videoPlayBackView {
    
    if (nil == _videoPlayBackView) {
        _videoPlayBackView = [LYVideoPlayBackView viewWithXib];
    }
    return _videoPlayBackView;
}

- (WatchPlayBackViewController *)watchPlayBackVC {
    
    WS(weakSelf)
    if (nil == _watchPlayBackVC) {
        _watchPlayBackVC = [[WatchPlayBackViewController alloc] initWithNibName:@"WatchPlayBackViewController" bundle:nil];
        _watchPlayBackVC.isVideoLivingPage = YES;
        _watchPlayBackVC.VideoLivingPageShareBlock = ^{
            [weakSelf likeAction:nil];
        };
    }
    return _watchPlayBackVC;
}

- (UIView *)backgroundView {
    
    if (nil == _backgroundView) {
        _backgroundView = [[UIView alloc] init];
        if (isIPhoneX) {
            _backgroundView.frame = CGRectMake(0, 44, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        } else {
            _backgroundView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MoviePlayerViewHeightWithScreenRate());
        }
        _backgroundView.clipsToBounds = YES;
        _backgroundView.backgroundColor = [UIColor colorWithHexString:@"#333333"];
        [_backgroundView addSubview:self.watchPlayBackVC.view];
        self.watchPlayBackVC.view.frame = _backgroundView.bounds;
        [self.view bringSubviewToFront:_backgroundView];
        [self addChildViewController:self.watchPlayBackVC];
    }
    return _backgroundView;
}

- (UIImageView *)bottomImageview {
    
    if (nil == _bottomImageview) {
        _bottomImageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.buttonView.y - 60, SCREEN_WIDTH, 60)];
        _bottomImageview.image = [UIImage imageNamed:@"video_vertial_down"];
    }
    return _bottomImageview;
}

@end
